package cn.virens.web.components.open.wxmp.router.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import cn.virens.web.components.open.session.WxSessionManager;
import cn.virens.web.components.open.wxmp.WxMpServiceImpl;
import cn.virens.web.components.open.wxmp.router.WxMpRouterRuleHandler;
import cn.virens.web.components.open.wxmp.session.WxMpSessionMessage;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpKefuService;
import me.chanjar.weixin.mp.api.WxMpUserService;
import me.chanjar.weixin.mp.api.WxMpUserTagService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;

/**
 * 公共消息路由父类
 * 
 * @author virens
 */
public abstract class AbstractMessageHandler implements WxMpRouterRuleHandler {
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	protected @Autowired WxMpServiceImpl mWxService;

	@Override
	public final WxMpXmlOutMessage handle(WxMpSessionMessage wxMessage, WxSessionManager sessionManager) {
		logger.debug("收到来自微信的消息:" + String.valueOf(wxMessage));

		try {
			return handle0(wxMessage, sessionManager);
		} catch (Exception e) {
			logger.error("微信:" + e.getMessage(), e);
		} finally {
			wxMessage.putSession(sessionManager);
		}

		return null;
	}

	/**
	 * 路由处理
	 * 
	 * @param  wxMessage        消息体
	 * @param  sessionManager   session管理器
	 * @return
	 * @throws WxErrorException
	 */
	protected WxMpXmlOutMessage handle0(WxMpSessionMessage wxMessage, WxSessionManager sessionManager) throws Exception {
		return null;
	}

	/**
	 * 获取客服管理服务
	 * 
	 * @return
	 */
	protected WxMpKefuService getKefuService() {
		return mWxService.getKefuService();
	}

	/**
	 * 获取用户管理服务
	 * 
	 * @return
	 */
	protected WxMpUserService getUserService() {
		return mWxService.getUserService();
	}

	/**
	 * 获取用户标签服务
	 * 
	 * @return
	 */
	protected WxMpUserTagService getUserTagService() {
		return mWxService.getUserTagService();
	}

	/**
	 * 构造返回文本消息
	 * 
	 * @param  message
	 * @param  content
	 * @return
	 */
	protected WxMpXmlOutTextMessage text(WxMpSessionMessage message, String content) {
		WxMpXmlOutTextMessage answer = new WxMpXmlOutTextMessage();
		answer.setCreateTime(System.currentTimeMillis());
		answer.setFromUserName(message.getToUser());
		answer.setToUserName(message.getFromUser());
		answer.setContent(content);

		return answer;
	}

}
